package com.sun.sort.quick;

import java.util.Arrays;

public class quick1 {
    public static void main(String[] args) {
//        int[] arr = {-9,78,0,-567,70};
        int[] arr = {8,9,1,7,2,3,5,4,6,0};
        quick(arr,0,arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
    public static void quick(int[] arr,int left,int right){
        int l = left;
        int r = right;
        int pivot = arr[(left + right) / 2]; //中轴
        int temp = 0;
        while (l < r){
            //while循环的目的是让比pivot 值 小放到左边
            //比pivot值 放到右边
            while (arr[l] < pivot){
                //在pivot左边一直找，找大于等于pivot的值才退出
                l += 1;
            }
            while (arr[r] > pivot){
                r -= 1;
            }
            if (l >= r){
                break;
            }
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            //如果交换完后，发现这个arr[l]==pivot的值，前移
            if (arr[l] == pivot){
                r -= 1;
            }
            if (arr[r] == pivot){
                l += 1;
            }
        }
        //如果 l == r,必须l++ 否则会出现栈溢出
        if (l == r){
            l += 1;
            r -= 1;
        }
        if (left < r){
            quick(arr,left,r);
        }
        if (right > l){
            quick(arr,l,right);
        }
    }
}
